import sys
import time
import pygame

from sprite.missle import Missle
from sprite.tank import PlayerTank, EnemyTank
from surface.text import Text


class Game(object):
    _settings = None
    _state = None

    _move_sprite = []

    _player = None

    def __init__(self, setting, state):
        self._settings = setting
        self._state = state

        # 初始化玩家
        self._player = PlayerTank(500, 500)
        # 创建敌人
        for i in range(1, 6):
            self._move_sprite.append({'type': 'tank', 'value': EnemyTank()})

    def display(self, screen):
        self.draw(screen)
        self.listen_event()

    # 绘制游戏界面
    def draw(self, screen):
        # 显示分数文字
        text = Text('当前敌方坦克坦克:%d' % self.get_tank_count())
        text.display(screen, (5, 5))

        for t in self._move_sprite:
            sprite = t.get('value')
            if sprite.active:
                sprite.display(screen)
            else:
                self._move_sprite.remove(t)

        self._player.display(screen)
        # 监听事件
        self.listen_event()
        time.sleep(0.02)

    def get_tank_count(self):
        cont = 0
        for tank in self._move_sprite:
            if tank.get('type') == 'tank':
                cont = cont + 1
        return cont

    # 监听游戏事件
    def listen_event(self):
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                sys.exit()

            move_key = self._settings.keyboard.get('move')

            if e.type == pygame.KEYUP and e.key in move_key.keys():
                self._player.moveState = False

            if e.type == pygame.KEYDOWN and e.key in move_key.keys():
                self._player.direction = move_key[e.key]
                self._player.moveState = True

            if e.type == pygame.KEYDOWN and e.key == self._settings.keyboard.get('fire'):
                missle = Missle()
                missle.setTank(self._player)
                self._move_sprite.append({'type': 'missle', 'value': missle})
